package com.thinkingdata.datax.plugin.writer.check;

import com.alibaba.datax.common.util.Configuration;

import com.alibaba.fastjson.JSON;

import com.thinkingdata.datax.plugin.writer.Key;
import com.thinkingdata.datax.plugin.writer.exption.TaDataWriterErrorCode;
import com.thinkingdata.datax.plugin.writer.exption.TaDataWriterException;
import com.thinkingdata.datax.plugin.writer.meta.TaDataWriterColumn;
import com.thinkingdata.datax.plugin.writer.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: Felix.Wang
 * @email: Felix@thinkingdata.cn
 * @date: 2019/8/22-14:45
 * @describe: TA-writer job校验类
 */
public class JobConfigCheck {

    private static final Logger logger = LoggerFactory.getLogger(JobConfigCheck.class);

    private String appid;

    public void setAppid(String appid) {
        this.appid = appid;
    }





    public void checkMeta(Configuration configuration) {
        logger.info("== column校验 开始 ==");
        List<TaDataWriterColumn> columns = JSON.parseArray(configuration.getList(Key.COLUMN).toString(), TaDataWriterColumn.class);
        String dataType = configuration.getString(Key.TYPE);
        Map<String, TaDataWriterColumn> taDataWriterColumnImmutableMap = columns.stream().collect(Collectors.toMap(TaDataWriterColumn::getColTargetName, Function.identity(), (key1, key2) -> key2));
        Object accountIdObj = taDataWriterColumnImmutableMap.get("#account_id");
        Object distinctIdObj = taDataWriterColumnImmutableMap.get("#distinct_id");
        Object timeObj = taDataWriterColumnImmutableMap.get("#time");
        if (accountIdObj == null && distinctIdObj == null) {
            logger.error("配置中[#account_id]与[#distinct_id]不能都为空");
            throw new TaDataWriterException(TaDataWriterErrorCode.ID_ERROR, "配置中[#account_id]与[#distinct_id]不能都不存在");
        }
        if (timeObj == null) {
            logger.error("配置中[#time]字段不能为空");
            throw new TaDataWriterException(TaDataWriterErrorCode.TIME_ERROR, "配置中[#time]字段不存在");
        }
        if (Constants.EVENT.equals(dataType)) {
            Object eventNameObj = taDataWriterColumnImmutableMap.get("#event_name");
            if (eventNameObj == null) {
                logger.error("配置中[#event_name]字段不存在");
                throw new TaDataWriterException(TaDataWriterErrorCode.EVENT_NAME_ERROR, "配置中[#event_name]字段不存在");
            }
        }
        System.out.println(JSON.toJSONString(columns));
        logger.info("== column校验 结束 ==");
    }

}
